﻿using System;
using System.Linq;

using MvcCms.Data.DynamicLINQ;
using MvcCms.Service.Models;

namespace MvcCms.Service.Code.DataTables
{
    public static class DataTablesSort
    {
        public static IQueryable Sort(DataTablesRequest dataTablesRequest, IQueryable query, string[] columnNames)
        {            
            for (int i = 0; i < dataTablesRequest.iSortingCols; i++) 
            {                
                int columnNumber = dataTablesRequest.iSortCol[i];
                string columnName = columnNames[columnNumber];
                
                string sortDirection = dataTablesRequest.sSortDir[i];
                //ummm, yes this is very very cool... very thank you d fowler
                if (sortDirection == "asc")
                {
                    if (i == 0) { query = query.DynamicOrderBy(d => d[columnName]); }
                    else { query = query.DynamicThenBy(d => d[columnName]); }
                }
                else
                {
                    if (i == 0) { query = query.DynamicOrderByDescending(d => d[columnName]); }
                    else { query = query.DynamicThenByDescending(d => d[columnName]); }
                }
            }
            return query;
        }
    }
}
